﻿using System;
using System.Text;
using PreeRegisterModel;
using Newtonsoft.Json.Linq;
using System.Web;
using System.Collections.Generic;

namespace PreeRegisterBLL
{
    public class CancelOrderBLL
    {
        /// <summary>
        /// 长治和平取消预约 患者发起
        /// </summary>
        /// <param name="xml">请求信息</param>
        /// <returns></returns>
        public static CancelOrderResponseModel CancelOrder(CancelOrderRequestModel request, OrderInfoModel orderInfo)
        {
            string strRef = "";
            string ls_err = "";

            try
            {
                CancelOrderResponseModel model = new CancelOrderResponseModel();
                CancelOrderModel Result = new CancelOrderModel();
                Result = CancelPreeOrder_CZHP(request, orderInfo, ref ls_err);

                if (ls_err != "")
                {
                    model.code = "-1";
                    model.msg = ls_err;
                    model.result = Result;
                    return model;
                }
                else
                {
                    model.code = "1";
                    model.msg = strRef;
                    model.result = Result;
                }
                return model;
            }
            catch (Exception err)
            {
                throw;
            }
        }

        /// <summary>
        /// 长治和平取消预约 患者发起
        /// </summary>
        /// <param name="request">请求数据</param>
        /// <param name="ls_err">返回信息</param>
        /// <returns></returns>
        private static CancelOrderModel CancelPreeOrder_CZHP(CancelOrderRequestModel request, OrderInfoModel orderInfo, ref string ls_err)
        {
            CancelOrderModel Result = new CancelOrderModel();
            try
            {
                string url_cancelorder = CommonBLL.GetConfig("CZHP_ADDR") + "CancelOutPatientAppointment?parameters=";
                StringBuilder head = new StringBuilder();
                StringBuilder body = new StringBuilder();
                head.Append("{head:\"\"");
                body.Append("{");
                body.AppendFormat("\"AppointmentCode\": \"{0}\",", request.iid);
                body.Append("\"Patient\": {");
                body.AppendFormat("\"IdentityCard\":\"{0}\",", orderInfo.card);
                body.Append("\"PatientCode\": \"\",");
                body.Append("\"PatientCardCode\": \"\",");
                body.AppendFormat("\"PatientName\": \"{0}\",", request.name);
                body.AppendFormat("\"Gender\": \"{0}\",", orderInfo.gender);
                body.AppendFormat("\"Birthday\": \"{0}\",", orderInfo.birth);
                body.AppendFormat("\"Address\": \"{0}\",", orderInfo.addr);
                body.AppendFormat("\"Telephone\": \"{0}\",", request.tel);
                body.AppendFormat("\"Age\": \"{0}\",", orderInfo.birth == "" ? "1" : CommonBLL.GetAgeByBirthdate(Convert.ToDateTime(orderInfo.birth)));
                body.Append("\"AgeUnit\": \"岁\"");
                body.Append("},");
                body.Append("\"WorkDetail\": {");
                body.AppendFormat("\"Code\": \"{0}\"", request.iid);
                body.Append("},");
                body.Append("\"Indextype\": \"\",");
                body.Append("\"AppointmentType\": \"\",");
                body.Append("\"SocialSecurityType\": \"\",");
                body.Append("\"VisitType\": \"\",");
                body.AppendFormat("\"AppointmentSource\": \"{0}\",", request.source);
                body.Append("\"VisitAgain\": \"\"");
                body.Append("}");
                CommonBLL.WriteFile_New(CommonBLL.bizCode_cancelorder, "1：取消预约接口请求body明文：\r\n" + CommonBLL.ConvertJsonString(body.ToString()));
                string postData_cacelorder = string.Format("{0},body:\"{1}", head.ToString(), HttpUtility.UrlEncode(Security.Base64.EncodeBase64(body.ToString())));
                postData_cacelorder += "\"}";
                url_cancelorder += postData_cacelorder;
                CommonBLL.WriteFile_New(CommonBLL.bizCode_cancelorder, "2：医取消预约接口请求密文：\r\n" + url_cancelorder);
                JObject obj_cancelorder = CommonBLL.HttpPost_CZHP(url_cancelorder);
                CommonBLL.WriteFile_New(CommonBLL.bizCode_cancelorder, "3：取消预约接口返回明文：\r\n" + CommonBLL.ConvertJsonString(obj_cancelorder.ToString()));
                string code_cancelorder = obj_cancelorder["code"].ToString();

                if (string.Equals(code_cancelorder, "1"))
                {
                    var mJObj_cancelorder = JArray.Parse(obj_cancelorder["result"].ToString());
                    foreach (var dr in mJObj_cancelorder)
                    {
                        //获取剩余可预约数
                        int count = 0;
                        WorkUpdateResponseModel workUpdateResponseModel = WorkBLL.GetWorkInfo(orderInfo.doctorid, request.wid, 9, out count);
                        Result.wid = request.wid;
                        Result.count = count.ToString();// dr["acount"].ToString();
                        Result.dcount = count.ToString();// dr["dcount"].ToString();
                        Result.tdate = dr["AppointmentOrder"]["RefundDate"].ToString();
                        ls_err = "";
                    }
                }
                else
                {
                    ls_err = obj_cancelorder["msg"].ToString(); ;
                    return Result;
                }
            }
            catch (Exception err)
            {
                throw err;
            }
            CommonBLL.WriteFile_New(CommonBLL.bizCode_cancelorder, ls_err);
            return Result;
        }



        /// <summary>
        /// 长治和平取消预约 【模拟调用模式取消预约】
        /// </summary>
        /// <param name="xml">请求信息</param>
        /// <returns></returns>
        public static CancelOrderResponseModel CancelOrder_New(CancelOrderRequestModel request)
        {
            string strRef = "取消预约成功。";
            string ls_err = "";

            try
            {
                CancelOrderResponseModel model = new CancelOrderResponseModel();
                CancelOrderModel Result = new CancelOrderModel();
                Result = CancelPreeOrder_CZHP_New(request, ref ls_err);

                if (ls_err != "")
                {
                    model.code = "-1";
                    model.msg = ls_err;
                    model.result = Result;
                    return model;
                }
                else
                {
                    model.code = "1";
                    model.msg = strRef;
                    model.result = Result;
                }
                return model;
            }
            catch (Exception err)
            {
                throw;
            }
        }

        /// <summary>
        /// 长治和平取消预约 【模拟调用模式取消预约】
        /// </summary>
        /// <param name="request">请求数据</param>
        /// <param name="ls_err">返回信息</param>
        /// <returns></returns>
        private static CancelOrderModel CancelPreeOrder_CZHP_New(CancelOrderRequestModel request, ref string ls_err)
        {
            CancelOrderModel Result = new CancelOrderModel();
            try
            {
                hars_appointmentrecord bll = new hars_appointmentrecord();
                if (bll.Update("3", request.oid, request.iid))
                {
                    CommonBLL.WriteFile_New(CommonBLL.bizCode_cancelorder, "2：取消预约修改状态成功：\r\n" + request.oid + " " + request.iid);

                    string strWHere = string.Format(" wid='{0}'", request.wid);
                    List<PreeRegisterModel.hars_appointmentrecord> list = bll.GetModelList(strWHere);
                    if (list != null && list.Count > 0)
                    {
                        Result.wid = request.wid;
                        Result.count = list[0].cout.ToString();
                        Result.dcount = list[0].cout.ToString();
                        Result.tdate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                        ls_err = "";
                    }
                    else
                    {
                        ls_err = "取消预约失败，未查询到相应记录";
                        return Result;
                    }

                }
                else
                {
                    ls_err = "取消预约失败，未查询到患者预约记录。";
                    return Result;
                }

            }
            catch (Exception err)
            {
                throw err;
            }
            CommonBLL.WriteFile_New(CommonBLL.bizCode_cancelorder, ls_err);
            return Result;
        }

        /// <summary>
        /// 长治和平取消预约  订单号超过约定的长度,系统自动取消时调用
        /// </summary>
        /// <param name="xml">请求信息</param>
        /// <returns></returns>
        public static CancelOrderResponseModel CancelOrder(OrderParameterModel_Index request)
        {
            string strRef = "";
            string ls_err = "";

            try
            {
                CancelOrderResponseModel model = new CancelOrderResponseModel();
                CancelOrderModel Result = new CancelOrderModel();
                Result = CancelPreeOrder_CZHP(request, ref ls_err);

                if (ls_err != "")
                {
                    model.code = "0";
                    model.msg = ls_err;
                    model.result = Result;
                    return model;
                }
                else
                {
                    model.code = "1";
                    model.msg = strRef;
                    model.result = Result;
                }
                return model;
            }
            catch (Exception err)
            {
                throw;
            }
        }

        /// <summary>
        /// 长治和平取消预约 订单号超过约定的长度,系统自动取消时调用
        /// </summary>
        /// <param name="request">请求数据</param>
        /// <param name="ls_err">返回信息</param>
        /// <returns></returns>
        private static CancelOrderModel CancelPreeOrder_CZHP(OrderParameterModel_Index request, ref string ls_err)
        {
            CancelOrderModel Result = new CancelOrderModel();
            try
            {
                string url_cancelorder = CommonBLL.GetConfig("CZHP_ADDR") + "CancelOutPatientAppointment?parameters=";
                StringBuilder head = new StringBuilder();
                StringBuilder body = new StringBuilder();
                /*
                 body.Append("{");
                    body.AppendFormat("\"AppointmentCode\": \"20170509004021350002\",");
                    \"Patient\": {");
                        body.AppendFormat("\"IdentityCard\": \"140421199305091624\",");
                        body.AppendFormat("\"PatientCode\": \"\",");
                       body.AppendFormat("\"PatientCardCode\": \"\",");
                        body.AppendFormat("\"PatientName\": \"张玉兰\",");
                       body.AppendFormat("\"Gender\": \"女\",");
                       body.AppendFormat("\"Birthday\": \"1993/05/09\",");
                        body.AppendFormat("\"Address\": \"\",");
                        body.AppendFormat("\"Telephone\": \"15203559621\",");
                        body.AppendFormat("\"Age\": \"24\",");
                        body.AppendFormat("\"AgeUnit\": \"岁\"");
                    body.AppendFormat("},");
                    body.AppendFormat("\"WorkDetail\": {");
                        body.AppendFormat("\"Code\": \"20170509004021350002\"");
                    body.AppendFormat("},");
                    body.AppendFormat("\"Indextype\": \"\",");
                    body.AppendFormat("\"AppointmentType\": \"\",");
                    body.AppendFormat("\"SocialSecurityType\": \"\",");
                    body.AppendFormat("\"VisitType\": \"\",");
                    body.AppendFormat("\"AppointmentSource\": \"趣医网\",");
                    body.AppendFormat("\"VisitAgain\": \"\"");
               body.Append("}");
                 */
                head.Append("{head:\"\"");
                body.Append("{");
                body.AppendFormat("\"AppointmentCode\": \"{0}\",", request.iid);
                body.Append("\"Patient\": {");
                body.AppendFormat("\"IdentityCard\":\"{0}\",", request.card);
                body.Append("\"PatientCode\": \"\",");
                body.Append("\"PatientCardCode\": \"\",");
                body.AppendFormat("\"PatientName\": \"{0}\",", request.name);
                body.AppendFormat("\"Gender\": \"{0}\",", request.gender);
                body.AppendFormat("\"Birthday\": \"{0}\",", request.birth);
                body.AppendFormat("\"Address\": \"{0}\",", request.addr);
                body.AppendFormat("\"Telephone\": \"{0}\",", request.tel);
                body.AppendFormat("\"Age\": \"{0}\",", request.birth == "" ? "1" : CommonBLL.GetAgeByBirthdate(Convert.ToDateTime(request.birth)));
                body.Append("\"AgeUnit\": \"岁\"");
                body.Append("},");
                body.Append("\"WorkDetail\": {");
                body.AppendFormat("\"Code\": \"{0}\"", request.iid);
                body.Append("},");
                body.Append("\"Indextype\": \"\",");
                body.Append("\"AppointmentType\": \"\",");
                body.Append("\"SocialSecurityType\": \"\",");
                body.Append("\"VisitType\": \"\",");
                body.AppendFormat("\"AppointmentSource\": \"{0}\",", request.source);
                body.Append("\"VisitAgain\": \"\"");
                body.Append("}");
                CommonBLL.WriteFile_New(CommonBLL.bizCode_cancelorder, "1：系统自动取消预约接口请求body明文：\r\n" + CommonBLL.ConvertJsonString(body.ToString()));
                string postData_cacelorder = string.Format("{0},body:\"{1}", head.ToString(), HttpUtility.UrlEncode(Security.Base64.EncodeBase64(body.ToString())));
                postData_cacelorder += "\"}";
                url_cancelorder += postData_cacelorder;
                CommonBLL.WriteFile_New(CommonBLL.bizCode_cancelorder, "2：系统自动取消预约接口请求密文：\r\n" + url_cancelorder);
                JObject obj_cancelorder = CommonBLL.HttpPost_CZHP(url_cancelorder);
                CommonBLL.WriteFile_New(CommonBLL.bizCode_cancelorder, "3：系统自动取消预约挂号接口返回明文：\r\n" + CommonBLL.ConvertJsonString(obj_cancelorder.ToString()));
                string code_cancelorder = obj_cancelorder["code"].ToString();

                if (string.Equals(code_cancelorder, "1"))
                {
                    var mJObj_cancelorder = JArray.Parse(obj_cancelorder["result"].ToString());
                    foreach (var dr in mJObj_cancelorder)
                    {
                        //获取剩余可预约数
                        int count = 0;
                        // WorkUpdateResponseModel workUpdateResponseModel = WorkBLL.GetWorkInfo(orderInfo.doctorid, request.wid, 9, out count);
                        Result.wid = request.wid;
                        Result.count = count.ToString();// dr["acount"].ToString();
                        Result.dcount = count.ToString();// dr["dcount"].ToString();
                        Result.tdate = dr["AppointmentOrder"]["RefundDate"].ToString();
                        ls_err = "";
                    }
                }
                else
                {
                    ls_err = obj_cancelorder["msg"].ToString(); ;
                    return Result;
                }
            }
            catch (Exception err)
            {
                throw err;
            }
            CommonBLL.WriteFile_New(CommonBLL.bizCode_cancelorder, ls_err);
            return Result;
        }

        /// <summary>
        /// 退费接口
        /// </summary>
        /// <param name="orderInfo"></param>
        /// <returns></returns>
        public static RegisterFadeResponseModel RegisterFade(OrderInfoModel orderInfo)
        {
            RegisterFadeResponseModel Result = new RegisterFadeResponseModel();
            try
            {
                string url_cancelorder = CommonBLL.GetConfig("CZHP_ADDR") + "CancelOutPatientAppointment?parameters=";
                StringBuilder head = new StringBuilder();
                StringBuilder body = new StringBuilder();
                head.Append("{head:\"\"");
                body.Append("{");
                body.AppendFormat("\"AppointmentCode\": \"{0}\",", orderInfo.iid);
                body.Append("\"Patient\": {");
                body.AppendFormat("\"IdentityCard\":\"{0}\",", orderInfo.card);
                body.Append("\"PatientCode\": \"\",");
                body.Append("\"PatientCardCode\": \"\",");
                body.AppendFormat("\"PatientName\": \"{0}\",", orderInfo.name);
                body.AppendFormat("\"Gender\": \"{0}\",", orderInfo.gender);
                body.AppendFormat("\"Birthday\": \"{0}\",", orderInfo.birth);
                body.AppendFormat("\"Address\": \"{0}\",", orderInfo.addr);
                body.AppendFormat("\"Telephone\": \"{0}\",", orderInfo.tel);
                body.AppendFormat("\"Age\": \"{0}\",", orderInfo.birth == "" ? "1" : CommonBLL.GetAgeByBirthdate(Convert.ToDateTime(orderInfo.birth)));
                body.Append("\"AgeUnit\": \"岁\"");
                body.Append("},");
                body.Append("\"WorkDetail\": {");
                body.AppendFormat("\"Code\": \"{0}\"", orderInfo.iid);
                body.Append("},");
                body.Append("\"Indextype\": \"\",");
                body.Append("\"AppointmentType\": \"\",");
                body.Append("\"SocialSecurityType\": \"\",");
                body.Append("\"VisitType\": \"\",");
                body.AppendFormat("\"AppointmentSource\": \"{0}\",", orderInfo.source);
                body.Append("\"VisitAgain\": \"\"");
                body.Append("}");
                CommonBLL.WriteFile_New(CommonBLL.bizCode_registerFade, "1：退费接口请求body明文：\r\n" + CommonBLL.ConvertJsonString(body.ToString()));
                string postData_cacelorder = string.Format("{0},body:\"{1}", head.ToString(), HttpUtility.UrlEncode(Security.Base64.EncodeBase64(body.ToString())));
                postData_cacelorder += "\"}";
                url_cancelorder += postData_cacelorder;
                CommonBLL.WriteFile_New(CommonBLL.bizCode_registerFade, "2：退费接口请求密文：\r\n" + url_cancelorder);
                JObject obj_cancelorder = CommonBLL.HttpPost_CZHP(url_cancelorder);
                CommonBLL.WriteFile_New(CommonBLL.bizCode_registerFade, "3：退费接口返回明文：\r\n" + CommonBLL.ConvertJsonString(obj_cancelorder.ToString()));
                string code_cancelorder = obj_cancelorder["code"].ToString();

                if (string.Equals(code_cancelorder, "1"))
                {
                    Result.code = "1";
                    Result.msg = "退号成功！";
                }
                else
                {
                    Result.code = "0";
                    Result.msg = obj_cancelorder["msg"].ToString();
                }
            }
            catch (Exception err)
            {
                throw err;
            }
            CommonBLL.WriteFile_New(CommonBLL.bizCode_registerFade, Result.msg);
            return Result;
        }
    }
}
